// plugins/my-plugin.ts
import {computed, inject, type ComputedRef, type Ref, type App, ref} from 'vue'

export interface MyPluginOptions {
    prefix?: string
    theme?: 'light' | 'dark'
    maxNotifications?: number
}

export interface Notification {
    id: number
    message: string
    type: 'success' | 'error' | 'warning' | 'info'
    duration?: number
}

export interface MyPluginAPI {
    // 工具方法
    formatDate: (date: Date, format?: string) => string
    debounce: <T extends (...args: any[]) => any>(fn: T, delay: number) => T

    // 状态管理
    theme: Ref<'light' | 'dark'>
    toggleTheme: () => void

    // 通知系统
    notifications: Ref<Notification[]>
    showNotification: (message: string, type?: Notification['type']) => void
    removeNotification: (id: number) => void

    // 配置
    config: ComputedRef<MyPluginOptions>
}

// 插件实现
const MyPlugin = {
    install(app: App, options: MyPluginOptions = {}) {
        const {
            prefix = 'App',
            theme = 'light',
            maxNotifications = 5
        } = options

        // 工具方法
        const formatDate = (date: Date, format: string = 'YYYY-MM-DD'): string => {
            return "";
        }

        const debounce = <T extends (...args: any[]) => any>(fn: T, delay: number): T => {
            let timeoutId: number
            return ((...args: Parameters<T>) => {
                clearTimeout(timeoutId)
                timeoutId = setTimeout(() => fn(...args), delay)
            }) as T
        }

        // 主题管理
        const themeRef = ref<'light' | 'dark'>(theme)
        const toggleTheme = () => {
            themeRef.value = themeRef.value === 'light' ? 'dark' : 'light'
            document.documentElement.setAttribute('data-theme', themeRef.value)
        }

        // 通知系统
        const notifications = ref<Notification[]>([])
        let nextId = 1

        const showNotification = (message: string, type: Notification['type'] = 'info') => {
            const id = nextId++
            const notification: Notification = {
                id,
                message: `${prefix}: ${message}`,
                type,
                duration: 3000
            }

            notifications.value.push(notification)

            // 限制最大数量
            if (notifications.value.length > maxNotifications) {
                notifications.value.shift()
            }

            // 自动移除
            if (notification.duration) {
                setTimeout(() => {
                    removeNotification(id)
                }, notification.duration)
            }
        }

        const removeNotification = (id: number) => {
            const index = notifications.value.findIndex(n => n.id === id)
            if (index !== -1) {
                notifications.value.splice(index, 1)
            }
        }

        // 配置
        const config = computed(() => ({
            prefix,
            theme: themeRef.value,
            maxNotifications
        }))

        const pluginAPI: MyPluginAPI = {
            formatDate,
            debounce,
            theme: themeRef,
            toggleTheme,
            notifications,
            showNotification,
            removeNotification,
            config
        }

        // 全局属性（选项式API）
        app.config.globalProperties.$myPlugin = pluginAPI

        // 依赖注入（组合式API）
        app.provide('myPlugin', pluginAPI)

        // 全局组件
        app.component('NotificationList', {
            setup() {
                const {notifications, removeNotification} = inject('myPlugin') as MyPluginAPI
                return {notifications, removeNotification}
            },
            template: `
              <div class="notification-container">
                <div
                    v-for="notification in notifications"
                    :key="notification.id"
                    :class="['notification', 'notification-' + notification.type]"
                    @click="removeNotification(notification.id)"
                >
                  {{ notification.message }}
                </div>
              </div>
            `
        })

        // 自定义指令
        app.directive('focus', {
            mounted(el) {
                el.focus()
            }
        })

        // 初始化主题
        document.documentElement.setAttribute('data-theme', themeRef.value)
    }
}

export default MyPlugin

// 类型扩展
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $myPlugin: MyPluginAPI
    }
}

// 组合式函数hook
export function useMyPlugin(): MyPluginAPI {
    const plugin = inject('myPlugin')
    if (!plugin) {
        throw new Error('MyPlugin 未安装')
    }
    return <MyPluginAPI>plugin
}
